package alscript.lua.bridge.util.system;

import android.os.SystemClock;


import com.imy.luasupport.core.LuaCore;
import com.imy.luasupport.util.LLog;

import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.ZeroArgFunction;

import java.util.concurrent.TimeUnit;

import alscript.lua.bridge.util.BaseFunLib;
import alscript.lua.bridge.util.LibRegister;

@LibRegister(libName = "system")
public class SystemLib  extends BaseFunLib {
    private LuaCore core;
    public SystemLib(LuaCore luaCore) {
        this.core =luaCore;
    }

    @Override
    protected void addFunction(LuaTable lib) {
        lib.set("sleep",new Sleep());
        lib.set("stopLua",new StopLua() );
    }

    static final class StopLua extends ZeroArgFunction{

        @Override
        public LuaValue call() {
            try {
                LuaCore.get().stopLua();
            }catch (Exception e){
                return LuaValue.error("stop lua");
            }
            return null;
        }
    }
    static final class Sleep extends OneArgFunction {

        @Override
        public LuaValue call(LuaValue arg) {
            int checkint = arg.checkint();
            try {
                Thread thread = Thread.currentThread();
                LLog.i("ALog","线程等待开始:"+checkint +"name:"+thread.getName());
                Thread.sleep(checkint);
            } catch (InterruptedException e) {
                //这里是抛出了线程异常
                LLog.i("ALog","脚本停止");
                return LuaValue.error("stop lua") ;
            }
//                core.getLuaThread().
            return LuaValue.valueOf(0);
        }


    }
}
